<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  size="750"
	  :close-on-click-modal="false"
	>
		<el-scrollbar>
		<el-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="120px"
			label-position="top"
		>
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">基础信息</span>
			</div>
			
			<el-form-item prop="name">
				<el-input v-model="formData.name" placeholder="请输入接口名称" />
			</el-form-item>
			
			<el-form-item prop="host">
				<el-input v-model="formData.host" placeholder="请输入接口host" />
			</el-form-item>
			
			<el-form-item prop="appKey">
				<el-input v-model="formData.appKey" placeholder="请输入接口appKey" />
			</el-form-item>
			
			<el-form-item prop="appSecret">
				<el-input v-model="formData.appSecret" placeholder="请输入接口appSecret" />
			</el-form-item>
			
			<el-form-item prop="camsApi">
				<el-input v-model="formData.camsApi" placeholder="请输入接口camsApi" />
			</el-form-item>
			
			<el-form-item prop="url">
				<el-input v-model="formData.url" placeholder="请输入接口地址" />
			</el-form-item>
			
			<el-form-item label="是否启用" prop="enabled" >
				<el-radio-group v-model="formData.enabled" >
				  <el-radio value="0">禁用</el-radio>
				  <el-radio value="1">启用</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<el-form-item label="默认执行" prop="defaultRunning" >
				<el-radio-group v-model="formData.defaultRunning" >
				  <el-radio value="0">手动</el-radio>
				  <el-radio value="1">自动</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">请求参数</span>
			</div>
			
			<div class="body-form-content">
				<div class="json-toolbar">
					<el-button type="primary" @click="handleAddJsonField">
						<el-icon><Plus /></el-icon>添加字段
					</el-button>
								</div>
								
				<el-table :data="jsonFields" border style="margin-bottom: 10px;">
					<el-table-column prop="name" label="参数名称" />
					<el-table-column prop="identifier" label="参数标识" width="120" />
					<el-table-column prop="required" label="参数必填" align="center" width="100">
						<template #default="scope">
						  <el-tag :type="scope.row.required == '1' ? 'danger' : 'info'">
							{{ scope.row.required == '1' ? "必填" : "可选" }}
						  </el-tag>
											</template>
										</el-table-column>
					<el-table-column prop="defaultValue" label="参数默认值" />
											<el-table-column label="操作" width="150" fixed="right">
												<template #default="{ row, $index }">
													<el-button link type="primary" @click="handleEditJsonField(row, $index)">编辑</el-button>
							<el-button link type="danger" @click="handleDeleteJsonField($index)">删除</el-button>
												</template>
											</el-table-column>
										</el-table>
				
				<el-form-item prop="rawContent">
									<MonacoEditor
						v-model="rawContent"
										:options="jsonEditorOptions"
						language="json"
						style="height: 300px;"
									/>
						</el-form-item>
			</div>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">分页请求</span>
			</div>
			
			<div class="pagination-settings">
				<el-form-item label="是否分页请求" prop="paginationType">
					<el-radio-group v-model="formData.paginationType">
						<el-radio :value="'0'">不分页</el-radio>
						<el-radio :value="'1'">请求体分页</el-radio>
					</el-radio-group>
				</el-form-item>
				
				<template v-if="formData.paginationType === '1'">
					<el-form-item label="当前页参数名" prop="pageField">
						<el-input v-model="formData.pageField" placeholder="请输入当前页参数名，例如：pageNo" />
					</el-form-item>
					
					<el-form-item label="每页数量参数名" prop="pageSizeField">
						<el-input v-model="formData.pageSizeField" placeholder="请输入每页数量参数名，例如：pageSize" />
					</el-form-item>
					
					<el-form-item label="起始页码" prop="pageNum">
						<el-input-number v-model="formData.pageNum" :min="0" :max="1000" placeholder="请输入起始页码" />
					</el-form-item>
					
					<el-form-item label="每页数量" prop="pageSize">
						<el-input-number v-model="formData.pageSize" :min="1" :max="1000" placeholder="请输入每页数量" />
					</el-form-item>
					
					<el-form-item label="处理线程数量" prop="threads">
						<el-input-number v-model="formData.threads" :min="1" :max="1000" placeholder="请输入处理线程数量" />
					</el-form-item>
					
					<el-form-item label="总数量字段" prop="totalField">
						<el-input v-model="formData.totalField" placeholder="请输入总数量字段名，例如：total" />
					</el-form-item>
				</template>
			</div>
			
			<!-- 测试结果展示区域 -->
				<div v-if="testResult" class="test-result">
					<div class="result-header">
						<div class="status-code">
						<span class="label">状态码:</span>
						<el-tag :type="testResult.statusCode === 200 ? 'success' : 'danger'">
								{{ testResult.statusCode }}
							</el-tag>
						</div>
					</div>

					<el-tabs v-model="responseTab">
						<el-tab-pane label="响应体" name="body">
							<div class="response-body">
								<div class="response-toolbar">
									<el-radio-group v-model="responseFormat" size="small">
										<el-radio-button value="json">JSON</el-radio-button>
										<el-radio-button value="xml">XML</el-radio-button>
										<el-radio-button value="text">Text</el-radio-button>
									</el-radio-group>
								</div>
								<div class="response-content-wrapper">
									<MonacoEditor
										v-if="testResult && responseContent"
										:key="responseContent"
										v-model="responseContent"
										:language="responseFormat === 'xml' ? 'text' : responseFormat"
										:options="monacoOptions"
										class="response-editor"
									/>
									<div v-else-if="testResult" class="empty-response">
										<el-empty description="无响应内容" />
									</div>
								</div>
							</div>
						</el-tab-pane>
						<el-tab-pane label="响应头" name="headers">
							<div class="headers-list">
								<div v-for="(header, index) in testResult.headers" :key="index" class="header-item">
									<span class="header-name">{{ header.name }}:</span>
									<span class="header-value">{{ header.value }}</span>
								</div>
							</div>
						</el-tab-pane>
					</el-tabs>
				</div>
		</el-form>
		</el-scrollbar>
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
			<el-button 
			  type="success" 
			  @click="handleTest" 
			  :loading="loading" 
			  :disabled="!formData.id"
			>测 试</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
	</el-drawer>
	<EditParamFieldDrawer  
		ref="editParamFieldDrawerRef" 
		@success="handleEditParamSuccess"
		@parse-fields="handleParseFields"
	/>
</template>

<script lang="ts" setup>
	import EditParamFieldDrawer from '@/components/DataWorkflow/components/EditParamFieldDrawer.vue';
	import HttpAPI from "@/api/biz/http";
	import { ElMessage } from 'element-plus';
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	// 修改 Monaco Editor worker 配置
	// import * as monaco from 'monaco-editor';
	// import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
	// import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
	// import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution';
	const loading = ref(false);
	const dialog = ref({
		visible: false,
		title: '',
	});
	const formRef = ref<any>();
	const editParamFieldDrawerRef=ref();
	const jsonEditorOptions = {
		theme: 'vs-dark',
		language: 'json',
		readOnly: true,
		automaticLayout: true,
		scrollBeyondLastLine: true,
		minimap: { enabled: false },
		lineNumbers: 'on',
		folding: true,
		wordWrap: 'on',
		fontSize: 14,
		tabSize: 2,
		suggestOnTriggerCharacters: true,
		formatOnPaste: true,
		formatOnType: true,
		suggest: {
			preview: true,
			showWords: true,
			showSnippets: true
		},
		contextmenu: true
	};
	
	const jsonFields = ref<Array<any>>([]);
	
	const rawContent=ref<any>();

	const formData = ref<any>({
		id: "",
		name: "",
		host: '',
		appKey: '',
		appSecret: '',
		camsApi: '',
		enabled:'0',
		defaultRunning:'0',
		threads:10,
		paginationType: '0',
		pageField: '',
		pageSizeField: '',
		pageNum:1,
		pageSize: 10,
		totalField: '',
		url:'',
		method:'POST',
		bodyType:'raw-json',
		clientType:'1',
		rawContent: '',
		authType:'AK_SK',
	});

	const formRules = {
		name: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
		host: [{ required: true, message: '请输入接口host', trigger: 'blur' }],
		appKey: [{ required: true, message: '请输入接口appKey', trigger: 'blur' }],
		appSecret: [{ required: true, message: '请输入接口appSecret', trigger: 'blur' }],
		camsApi: [{ required: true, message: '请输入接口camsApi', trigger: 'blur' }],
		enabled: [{ required: true, message: '请输选择是否可用', trigger: 'blur' }],
		defaultRunning: [{ required: true, message: '请选择是否默认启动', trigger: 'blur' }],
		url: [{ required: true, message: '请输入接口地址', trigger: 'blur' }],
		paginationType: [{ required: true, message: "请选择是否分页请求", trigger: "change" }],
		totalField: [{ required: true, message: "请输入数据量取值字段", trigger: "change" }],
		threads: [{ required: true, message: "请输入处理线程数量", trigger: "change" }],
		pageField: [
			{ 
				required: true, 
				message: '请输入当前页参数名', 
				trigger: 'blur',
				validator: (_rule: any, value: string) => {
					if (formData.value.paginationType === '1' && (!value || value.trim() === '')) {
						return new Error('请输入当前页参数名');
					}
					return true;
				}
			}
		],
		pageSizeField: [
			{
				required: true,
				message: '请输入每页数量参数名',
				trigger: 'blur',
				validator: (_rule: any, value: string) => {
					if (formData.value.paginationType === '1' && (!value || value.trim() === '')) {
						return new Error('请输入每页数量参数名');
					}
					return true;
				}
			}
		],
		pageSize: [
			{
				required: true,
				message: '请输入默认每页数量',
				trigger: 'blur',
				validator: (_rule: any, value: number) => {
					if (formData.value.paginationType === '1' && (!value || value < 1)) {
						return new Error('请输入有效的默认每页数量');
					}
					return true;
				}
			}
		],
		pageNum: [
			{
				required: true,
				message: '请输入起始页码',
				trigger: 'blur',
				validator: (_rule: any, value: number) => {
					if (formData.value.paginationType === '1' && (value === undefined || value < 0)) {
						return new Error('请输入有效的起始页码');
					}
					return true;
				}
			}
		],
	};

	const submitForm = async () => {
		if (!formRef.value) return;
		await formRef.value.validate();
		loading.value = true;
		try {
			formData.value.rawContent=JSON.stringify(jsonFields.value)
			await HttpAPI.save(formData.value);
			ElMessage.success('保存成功');
			closeDialog();
		} catch (error) {
			ElMessage.error('保存失败');
		} finally {
			loading.value = false;
		}
	};
	
	async function openDialog(row?: any, type?: string) {
		dialog.value = {
			visible: true,
			title: type === 'add' ? '新增综合安防管理平台HTTP数据源' : '编辑综合安防管理平台HTTP数据源'
		};
		formData.value=row||{
			id: "",
			name: "",
			host: '',
			appKey: '',
			appSecret: '',
			camsApi: '',
			enabled:'0',
			defaultRunning:'0',
			threads:10,
				paginationType: '0',
			pageField: '',
			pageSizeField: '',
			pageNum:1,
				pageSize: 10,
			totalField: '',
			authType:'AK_SK',
			url:'',
			method:'POST',
			clientType:'1',
			bodyType:'raw-json',
			rawContent: '',
		};
		if(formData.value?.rawContent){
			jsonFields.value=JSON.parse(formData.value?.rawContent);
			updateJsonContent();
		}
	}

	const closeDialog = () => {
		dialog.value.visible = false;
		resetForm();
		emit('closeDialog');
		jsonFields.value=[];
		rawContent.value=''
		testResult.value = null; 
		responseContent.value = ''; 
	};

	const resetForm = () => {
		formRef.value?.resetFields();
			formData.value = {
			id: "",
			name: "",
			host: '',
			appKey: '',
			appSecret: '',
			camsApi: '',
			enabled:'0',
			defaultRunning:'0',
			threads:10,
			paginationType: '0',
			pageField: '',
			pageSizeField: '',
			pageNum:1,
			pageSize: 10,
			totalField: '',
			authType:'AK_SK',
			url:'',
			method:'POST',
			clientType:'1',
			bodyType:'raw-json',
			rawContent: '',
		};
	};

	const handleAddJsonField = () => {
		editParamFieldDrawerRef.value.openDialog(-1,null,'add');
	};

	const handleEditJsonField = (row: any, _index: number) => {
		editParamFieldDrawerRef.value.openDialog(_index,row,'edit');
	};

	const handleDeleteJsonField = (index: number) => {
		jsonFields.value.splice(index, 1);
		updateJsonContent();
	};

	const handleEditParamSuccess=(index:number,data:any)=>{
		try {
			if (!jsonFields.value) {
				jsonFields.value = [];
			}
			if (index > -1) {
				jsonFields.value[index] = data;
			} else {
				jsonFields.value.push(data);
			}
			updateJsonContent();
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}

	const handleParseFields = (fields: any[]) => {
		try {
			// 将解析的字段添加到现有字段列表中
			fields.forEach(field => {
				if (!jsonFields.value) {
					jsonFields.value = [];
				}
				// 检查是否已存在相同标识的字段
				const existingIndex = jsonFields.value.findIndex(f => f.identifier === field.identifier);
				if (existingIndex > -1) {
					// 更新已存在的字段
					jsonFields.value[existingIndex] = field;
				} else {
					// 添加新字段
					jsonFields.value.push(field);
				}
			});
			
			// 更新JSON预览
			updateJsonContent();
			
			ElMessage.success(`成功解析 ${fields.length} 个字段`);
		} catch (error) {
			console.error('处理解析字段失败:', error);
			ElMessage.error('处理解析字段失败');
		}
	};

	const updateJsonContent = () => {
		try {
			const jsonObj: Record<string, any> = {};
			jsonFields.value.forEach(field => {
				let current = jsonObj;
				const paths = field.identifier.split('.');
				paths.forEach((path: string, index: number) => {
					if (index === paths.length - 1) {
						current[path] = field.defaultValue;
			} else {
						current[path] = current[path] || {};
						current = current[path];
					}
				});
			});
			rawContent.value = JSON.stringify(jsonObj, null, 2);
		} catch (error) {
			console.error('更新JSON内容失败:', error);
		}
	};
	const emit = defineEmits(['closeDialog']);
	defineExpose({
		openDialog,
		closeDialog
	});

	// 测试相关的响应式变量
	const responseTab = ref('body');
	const responseFormat = ref<'json' | 'xml' | 'text'>('json');
	const responseContent = ref('');
	const testResult = ref<any>(null);
	
	// Monaco编辑器配置
	const monacoOptions = {
		readOnly: true,
		theme: 'vs-dark',
		minimap: { enabled: false },
		scrollBeyondLastLine: false,
		automaticLayout: true
	};
	
	// 测试请求处理函数
	// 修改测试方法
	const handleTest = () => {
		if (!formData.value?.id) {
			ElMessage.warning('请先保存接口后再进行测试');
			return;
		}

		loading.value = true;
		testResult.value = null; // 清空之前的测试结果
		responseContent.value = ''; // 清空之前的响应内容

		HttpAPI.test(formData.value.id)
			.then((result:any) => {
				console.log('测试结果:', result); // 添加日志
				testResult.value = result;
				responseTab.value = 'body';
				
				// 设置响应内容
				const content = result.body || '';
				
				// 自动检测响应格式
				const contentType = result.headers.find((h:any) => 
					h.name.toLowerCase() === 'content-type'
				)?.value?.toLowerCase() || '';

				if (contentType.includes('application/json')) {
					responseFormat.value = 'json';
					try {
						const obj = JSON.parse(content);
						responseContent.value = JSON.stringify(obj, null, 2);
					} catch {
						responseContent.value = content;
					}
				} else if (contentType.includes('application/xml') || contentType.includes('text/xml')) {
					responseFormat.value = 'xml';
					responseContent.value = formatXML(content);
				} else {
					responseFormat.value = 'text';
					responseContent.value = content;
				}
			})
			.catch((error:any) => {
				console.error('测试失败:', error); // 添加错误日志
				ElMessage.error(error.message || '测试失败');
				testResult.value = null;
				responseContent.value = '';
			})
			.finally(() => {
				loading.value = false;
			});
	};

	// 添加 XML 格式化函数
	const formatXML = (xml: string) => {
		if (!xml.trim().startsWith('<')) return xml;
		
		try {
			return xml
				.replace(/></g, '>\n<')
				.replace(/(<\/?[^>]+>)/g, '$1\n')
				.split('\n')
				.filter(line => line.trim())
				.map(line => {
					const match = line.match(/^\s*/);
					const indentLevel = match ? match[0].length : 0;
					return '  '.repeat(indentLevel / 2) + line.trim();
				})
				.join('\n');
		} catch {
			return xml;
		}
	};
	
	// 5. 监听器
	watch([() => responseFormat.value, () => testResult.value], () => {
		if (!testResult.value?.body) {
			responseContent.value = '';
			return; 
		}
	
		const content = testResult.value.body;
		
		try {
			switch (responseFormat.value) {
				case 'json':
					try {
						const obj = JSON.parse(content);
						responseContent.value = JSON.stringify(obj, null, 2);
					} catch {
						responseContent.value = content;
					}
					break;
				case 'xml':
					if (content.trim().startsWith('<?xml') || content.trim().startsWith('<')) {
						responseContent.value = content
							.replace(/></g, '>\n<')
							.replace(/(<\/?[^>]+>)/g, '$1\n')
							.split('\n')
							.filter((line:any) => line.trim())
							.map((line:any) => {
								const match = line.match(/^\s*/);
								const indentLength = match ? match[0].length : 0;
								return '  '.repeat(indentLength / 2) + line.trim();
							})
							.join('\n');
		} else {
						responseContent.value = content;
					}
					break;
				default:
					responseContent.value = content;
			}
		} catch (e) {
			console.warn('格式化响应内容失败:', e);
			responseContent.value = content;
		}
	}, { immediate: true });
</script>

<style scoped>
	.title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: #1f2329;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
	    content: "";
	    width: 2px;
	    height: 14px;
	    background: var(--el-color-primary);
	    position: absolute;
	    top: 50%;
	    transform: translateY(-50%);
	    left: 0;
	}
	
	.pagination-settings {
		padding: 16px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
		margin-bottom: 18px;
	}

	.body-form-content {
		border: 1px solid var(--el-border-color-light);
		border-radius: 4px;
		padding: 16px;
		background-color: var(--el-bg-color-overlay);
	}

	.json-toolbar {
		margin-bottom: 10px;
		padding: 8px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
	}

	/* 测试结果样式 */
	.test-result {
		margin-top: 20px;
		border: 1px solid var(--el-border-color);
		border-radius: 4px;

		.result-header {
			padding: 12px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid var(--el-border-color);
			
			.status-code {
				display: flex;
				align-items: center;
				gap: 8px;
				
				.label {
					font-weight: 500;
				}
			}
		}
		
		.response-editor {
			height: 300px;
			border: none;
		}
		
		.headers-list {
			padding: 12px;
			
			.header-item {
				padding: 4px 0;
				display: flex;
				gap: 8px;
				
				.header-name {
					color: var(--el-text-color-secondary);
					min-width: 120px;
				}
				
				.header-value {
					color: var(--el-text-color-primary);
					word-break: break-all;
				}
			}
		}
	}

	.response-body {
		position: relative;
		height: 300px;
		display: flex;
		flex-direction: column;
	}

	.response-toolbar {
		padding: 8px;
		border-bottom: 1px solid var(--el-border-color);
	}

	.response-content-wrapper {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.empty-response {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: var(--el-fill-color-light);
	}
</style>